<?php

namespace Common\Logic;

/**
 * 统计业务逻辑
 *
 * @author songanwei
 * @date 2016-1-18
 */
class ReportLogic extends \Common\Controller\BaseController {

    public $levelMap = array(
            'zh_cn' => array(
                'level' => '客人',
                'ci' => '次',
            ),
            'en_us' => array(
                'level' => 'Guest',
                'ci' => 'times',
            ),
            'zh_tw' => array(
                'level' => '客人',
                'ci' => '次',
            ),
        );

    /**
     * 根据日期、类型计算收支总额
     * @modify songanwei 2015-01-22
     * @param integer $hotelId 客栈ID
     * @param date $startDate 查询开始日期
     * @param date $endDate 查询结束日期
     * @return type
     */
    public function getSummary($hotelId, $startDate, $endDate) {
        return $this->__singleGet('_getSummary', array($hotelId, $startDate, $endDate));
    }
    protected function _getSummary($hotelId, $startDate, $endDate = null) {
        if (is_null($endDate)) {
            $endDate = $startDate;
        }
        $startDate = $startDate . ' 00:00:00';
        $endDate = $endDate . ' 23:59:59';

        // 获取客栈收款记录
        $orderPayRecordModel = D('OrderPayRecord');
        $hotelPayRecords = $orderPayRecordModel->getInfoByHotel($hotelId, $startDate, $endDate);

        // 检查操作者是否子管理员,若是,需要根据房间权限过滤父订单
        if (MODULE_NAME != 'Extend' && !empty($hotelPayRecords)) {
            // 获取房间权限权限
            $adminId = getUserId();
            $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
            if (!$adminAuthorityLogic->checkIsAdmin($adminId, $hotelId)) {
                $accountLogic = A('Common/Account', 'Logic');
                $roomAuthority = $accountLogic->getAdminRoomAuthority($adminId, $hotelId);

                if (empty($roomAuthority)) {
                    $hotelPayRecords = array();
                } else {
                    // 删除无房间权限的父订单的收款记录
                    $orderIds = array_column($hotelPayRecords, 'orderinfo_id');
                    $orderRoomModel = D('OrderRoom');
                    $orderRooms = $orderRoomModel->getInfoByOrder($orderIds);
                    // 过滤出有权限的子订单,再过滤出有权限的父订单
                    $orderRooms = fliterArrayByKey($orderRooms, 'roominfo_id', $roomAuthority);
                    $orderIds = array_column($orderRooms, 'orderinfo_id');
                    $hotelPayRecords = fliterArrayByKey($hotelPayRecords, 'orderinfo_id', $orderIds);
                }
            }
        }

        $receipt = $refund = $deposit = $refundDeposit = 0.00;
        //分别计算日期段内的收入、押金、支出
        foreach ($hotelPayRecords as $hotelPayRecordItem) {
            switch ($hotelPayRecordItem['type']) {
                case PAY_CHANGE_RECEIPT:// 收款
                    $receipt += (double)$hotelPayRecordItem['pay'];
                    break;
                case PAY_CHANGE_DEPOSIT:// 收押金
                    $deposit += (double)$hotelPayRecordItem['pay'];
                    break;
                case PAY_CHANGE_REFUND:// 退款
                    $refund += (double)$hotelPayRecordItem['pay'];
                    break;
                case PAY_CHANGE_DEPOSIT_BACK:// 退押金
                    $refundDeposit += (double)$hotelPayRecordItem['pay'];
                    break;
                default;
                    // 收入 加上其他消费 （不含待收款）
                    if ($hotelPayRecordItem['hotelpay_id'] != 0) {
                        $receipt += (double)$hotelPayRecordItem['pay'];
                    }
                    break;
            }
        }
        unset($hotelPayRecordItem);

        //返回数据结果
        $summaryData = array(
            'receipt' => $receipt,
            'refund' => $refund,
            'deposit' => $deposit,
            'refundDeposit' => $refundDeposit
        );
        return $summaryData;
    }


    public function getRoomReport($hotelId, $startDate, $endDate) {
        return $this->__singleGet('_getRoomReport', array($hotelId, $startDate, $endDate));
    }
    protected function _getRoomReport($hotelId, $startDate, $endDate) {
        $orderRoomReportModel = D('OrderRoomReport');
        $orderRoomReports = $orderRoomReportModel->getInfsByHotelDate($hotelId, $startDate, $endDate);
        //如果检查包含今天的数据
        if ($endDate && (strtotime($startDate) <= time()) && time() <= strtotime($endDate . " 23:59:59")) {
            $todayOrderRoomReports = $this->getTodayRoomDetail($hotelId, date('Y-m-d'));
            foreach ($todayOrderRoomReports as $todayOrderRoomReport) {
                $orderRoomReports[] = $todayOrderRoomReport;
            }
        }
        
        // 检查操作者是否子管理员,若是,需要根据房间权限过滤房间统计数据
        if (MODULE_NAME != 'Extend') {
            // 获取房间权限权限
            $adminId = getUserId();
            $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
            $needFilterRoom = false;
            if (!$adminAuthorityLogic->checkIsAdmin($adminId, $hotelId)) {
                $needFilterRoom = true;
                $accountLogic = A('Common/Account', 'Logic');
                $roomAuthority = $accountLogic->getAdminRoomAuthority($adminId, $hotelId);

                $orderRoomReports = fliterArrayByKey($orderRoomReports, 'roominfo_id', $roomAuthority);
            }
        }

        // 检查操作者是否子管理员,若是,需要根据房间权限过滤房间数据
        $roomLogic = A('Common/Room', 'Logic');
        $roomInfos = $roomLogic->getCanCheckinRoomByDate($hotelId, $startDate . ' 00:00:00', $startDate . ' 23:59:59');

        if (MODULE_NAME != 'Extend' && $needFilterRoom) {
            $roomInfos = fliterArrayByKey($roomInfos, 'id', $roomAuthority);
        }

        $data = array();
        $checkIn = $notCheckIn = $price = 0;
        foreach ($orderRoomReports as $orderRoomReport) {
            if ($orderRoomReport['status'] == 1) {
                $checkIn++;
            } elseif ($orderRoomReport['status'] == 0) {
                $notCheckIn++;
            }
            $price+= $orderRoomReport['price'];
        }

        $data = array(
            'roomTotal' => 0,
            'checkInCount' => $checkIn ? $checkIn : 0,
            'notCheckInCount' => $notCheckIn ? $notCheckIn : 0,
            'price' => empty($price) ? 0 : round($price / count($orderRoomReports), 2),
        );
        // 算出真正能入住的房间总数
        foreach ($roomInfos as $roomInfoItem) {
            $data['roomTotal'] += $roomInfoItem['canCheckinDays'];
        }
        unset($roomInfoItem);

        return $data;
    }

    /**
     * 查询财务收支信息
     * @modify trainyao 2016-01-19 创建
     * @modify trainyao 2016-07-01 增加房间权限限制
     * @param  integer   $hotelId   客栈id
     * @param  string   $startDate 开始日期
     * @param  string      $endDate   结束日期
     * @return array              信息数组
     */
    public function getHotelInOutComeData($hotelId, $startDate, $endDate) {
        return $this->__singleGet('_getHotelInOutComeData', array($hotelId, $startDate, $endDate));
    }
    protected function _getHotelInOutComeData($hotelId, $startDate, $endDate = null) {
        if (is_null($endDate)) {
            $endDate = $startDate;
        }
        $startDate = $startDate;
        $endDate = $endDate;

        // 获取具体支付信息记录
        $orderLogic = A('Common/Order', 'Logic');
        try {
            $hotelPayRecords = $orderLogic->getHotelOrderPayInfoByDate($hotelId, $startDate, $endDate);
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }

        // 获取支付方式信息用作补充
        $hotelLogic = A('Common/Hotel', 'Logic');
        $payResource = $hotelLogic->getHotelPay($hotelId, true, null, true);
        $payResource = getArrayValueAsIndex($payResource, 'id');

        // 根据收款退款记录,生成客栈按日期收支记录
        // 下面用算法模拟记录是hotelPayReport表的数据结构
        $hotelPayReportExts = array();
        foreach ($hotelPayRecords as $key => $hotelPayRecordItem) {
            if ($hotelPayRecordItem['hotelpay_id'] == 0) {
                unset($hotelPayRecords[$key]);
                continue;
            }
            if (!isset($hotelPayReportExts[$hotelPayRecordItem['hotelpay_id']])) {
                $hotelPayReportExts[$hotelPayRecordItem['hotelpay_id']] = array();
            }

            if (in_array($hotelPayRecordItem['type'], array(PAY_CHANGE_RECEIPT, PAY_CHANGE_DEPOSIT)) || !in_array($hotelPayRecordItem['type'], [PAY_CHANGE_RECEIPT,PAY_CHANGE_DEPOSIT,PAY_CHANGE_REFUND,PAY_CHANGE_DEPOSIT_BACK])) {
                $income = $hotelPayRecordItem['pay'];
                $outcome = 0;
            } else if (in_array($hotelPayRecordItem['type'], array(PAY_CHANGE_REFUND, PAY_CHANGE_DEPOSIT_BACK))) {
                $outcome = $hotelPayRecordItem['pay'];
                $income = 0;
            }
            array_push($hotelPayReportExts[$hotelPayRecordItem['hotelpay_id']], array(
                'income' => $income,
                'outcome' => $outcome,
            ));
        }
        unset($hotelPayRecordItem);
        $hotelPayRecords = array_values($hotelPayRecords);

        $eachMethod = array(
            'in' => array(
                'total' => 0,
                'data' => array(),
            ),
            'out' => array(
                'total' => 0,
                'data' => array(),
            ),
            'total' => array(),
        );

        foreach ($hotelPayReportExts as $hotelPayId => $eachMethodPayRepots) {
            foreach ($eachMethodPayRepots as $hotelPayReport) {
                $income = $hotelPayReport['income'];
                $outcome = $hotelPayReport['outcome'];
                $eachMethod['out']['total'] += $outcome;
                $eachMethod['in']['total'] += $income;
                // 收入饼图数据
                if (!empty($income)) {
                    if (empty($eachMethod['in']['data'][$hotelPayId])) {
                        $eachMethod['in']['data'][$hotelPayId] = array(
                            'name' => $payResource[$hotelPayId]['name'],
                            'total' => $income,
                        );
                    } else {
                        $eachMethod['in']['data'][$hotelPayId]['total'] += $income;
                    }
                }

                // 支出饼图数据
                if (!empty($outcome)) {
                    if (empty($eachMethod['out']['data'][$hotelPayId])) {
                        $eachMethod['out']['data'][$hotelPayId] = array(
                            'name' => $payResource[$hotelPayId]['name'],
                            'total' => $outcome,
                        );
                    } else {
                        $eachMethod['out']['data'][$hotelPayId]['total'] += $outcome;
                    }
                }

                // 总节余柱状图数据
                if (empty($eachMethod['total'][$hotelPayId])) {
                    $eachMethod['total'][$hotelPayId] = array(
                        'name' => $payResource[$hotelPayId]['name'],
                        'value' => ($income - $outcome),
                    );
                } else {
                    $eachMethod['total'][$hotelPayId]['value'] += ($income - $outcome);
                }
            }
            unset($hotelPayReport);
        }
        unset($eachMethodPayRepots);

        // 算出百分比值
        $inTotal = $eachMethod['in']['total'];
        foreach ($eachMethod['in']['data'] as &$methodData) {
            $methodData['value'] = $methodData['total'] / $inTotal;
        }
        unset($methodData);
        $outTotal = $eachMethod['out']['total'];
        foreach ($eachMethod['out']['data'] as &$methodData) {
            $methodData['value'] = $methodData['total'] / $outTotal;
        }
        unset($methodData);

        // 生成第一页分页信息
        $hotelPayRecords = createPageInfo($hotelPayRecords, 1, C('PAGE_SIZE'));
        return array(
            'total' => array_values($eachMethod['total']),
            'in' => array_values($eachMethod['in']['data']),
            'out' => array_values($eachMethod['out']['data']),
            'info' => $hotelPayRecords['data'],
            'itemtotal' => $hotelPayRecords['total'],
            'pagetotal' => $hotelPayRecords['pageTotal'],
        );
    }

    /**
     * 返回客栈日期段内的房间状态
     * @modify songanwei 2016-01-20
     * @modify trainyao 2016-04-26    补没有算房间有效时间影响统计页面数据坑
     * @param integer $hotelId 客栈ID
     * @param date $startDate 查询开始日期 2016-01-19
     * @param date $endDate 查询结束日期
     * @return array {
        actualOccupancy(实住订单数),notCheckIn(客人未到店订单数),notSold(未售出房间数目),occupancyRate(入住率),price(平均价格),
            roomInfo(房型房间信息)=>[{roomtype_id,name, total, occupancyRate(房型入住率), price,
                    rooms=>[{id, name, canCheckinDays, total, actualOccupancy, occupancyRate, price, notCheckIn, notSold},{}]
                    }, {},..],
            notCheckInSeries(每天客人未到店订单数), notSoldSeries(每天未售出房间数), priceSeries(每天平均房价), occupancyRateSeries(每天入住率), actualOccupancySeries(每天实住订单数), incomeSeries(每天收入)
        }
     */
    public function getRoomDetail($hotelId, $startDate, $endDate, $type = 0) {
        //查询房型数据
        $roomTypeModel = D('RoomType');
        $orderRoomReportModel = D('OrderRoomReport');

        // 查询包含可入住天数的房间数据
        $roomLogic = A('Common/Room', 'Logic');
        $roomInfos = $roomLogic->getCanCheckinRoomByDate($hotelId, $startDate . ' 00:00:00', $endDate . ' 23:59:59');
        if ($type == 1) {
            $hourRoomModel = D('HourRoom');
            $hourRooms = $hourRoomModel->getInfosByHotel($hotelId);
            $hourRoomIds = array_column($hourRooms, 'roominfo_id');
        }
        if ($type == 2) {
            $longRoomModel = D('LongRoom');
            $longRooms = $longRoomModel->getInfosByHotel($hotelId);
            $longRoomIds = array_column($longRooms, 'roominfo_id');
        }
        // 检查是否需要检查房间权限
        if (MODULE_NAME != 'Extend') {
            // 获取房间权限权限
            $adminId = getUserId();
            $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
            if (!$adminAuthorityLogic->checkIsAdmin($adminId, $hotelId)) {
                $accountLogic = A('Common/Account', 'Logic');
                $roomAuthority = $accountLogic->getAdminRoomAuthority($adminId, $hotelId);
                // 去除无权限的房间信息
                $roomInfos = fliterArrayByKey($roomInfos, 'id', $roomAuthority);
            }
        }
        $roomInfos = getArrayValueAsIndex($roomInfos, 'id');

        // 过滤掉不在查询时间内的房间
        $endDateEnd = $endDate . ' 23:59:59';
        
        // 算出房型可入住房间数
        $roomTypeCanCheckinDays = array();
        $totalCanCheckinRoomCount = 0;
        if (!empty($roomInfos)) {
            foreach ($roomInfos as $roomId => $roomInfoItem) {
                //过滤钟点房
                if ($type === 1 &&!in_array($roomId, $hourRoomIds)) {
                    unset($roomInfos[$roomId]);
                    continue;
                }
                //过滤长租房
                if ($type === 2 &&!in_array($roomId, $longRoomIds)) {
                    unset($roomInfos[$roomId]);
                    continue;
                }
                // 房型可入住房间数
                if (!isset($roomTypeCanCheckinDays[$roomInfoItem['roomtype_id']])) {
                    $roomTypeCanCheckinDays[$roomInfoItem['roomtype_id']] = $roomInfoItem['canCheckinDays'];
                } else {
                    $roomTypeCanCheckinDays[$roomInfoItem['roomtype_id']] += $roomInfoItem['canCheckinDays'];
                }
                // 总可入住房间数
                $totalCanCheckinRoomCount += $roomInfoItem['canCheckinDays'];
            }
            unset($roomInfoItem);
        }
        // 总房间数
        $currentRoomTotal = count($roomInfos);

        //检查判断是否包含了今天在内的数据,取出可统计的入住数
        $startTime = strtotime($startDate);
        $endTime = strtotime($endDate);
        $orderRoomReports = [];
        $incomeDateReports = [];
        for ($i=$startTime; $i <= $endTime; $i+=86400) { 
            if ($type === 1) {
                $todayOrderRoomReports = $this->getTodayHourRoomDetail($hotelId, date('Y-m-d', $i));
                $todaySummary = $this->getTodayHourSummary($hotelId, date('Y-m-d', $i));
            } elseif ($type === 2){
                $todayOrderRoomReports = $this->getTodayMonthRoomDetail($hotelId, date('Y-m-d', $i));
                $todaySummary = $this->getTodayMonthSummary($hotelId, date('Y-m-d', $i));
            } else {
                $todayOrderRoomReports = $this->getTodayRoomDetail($hotelId, date('Y-m-d', $i));
                $todaySummary = $this->getTodaySummary($hotelId, date('Y-m-d', $i));
            }
            
            foreach ($todayOrderRoomReports as $todayOrderRoomReport) {
                //$todayOrderRoomReport['receipt'] = $todaySummary['receipt'];
                $orderRoomReports[] = $todayOrderRoomReport;
            }

            $incomeDateReports[$i] = $todaySummary['receipt'];
        }
        unset($todayOrderRoomReport);

        // 去除无权限的房间信息
        $orderRoomReports = array_values($orderRoomReports);
        if (MODULE_NAME != 'Extend' && isset($roomAuthority)) {
            $orderRoomReports = fliterArrayByKey($orderRoomReports, 'roominfo_id', $roomAuthority);
        }
        //转化数据、计算每一个房间每一天的相关情况，收入、实住、入住率、平均价格、未售出、未入住等等
        $orderRoomReportDatas = array();
        foreach ($orderRoomReports as $orderRoomReport) {
            if (!isset($orderRoomReportDatas[$orderRoomReport['roominfo_id']])) {
                $orderRoomReportDatas[$orderRoomReport['roominfo_id']] = array(
                    'roominfo_id' => $orderRoomReport['roominfo_id'],
                    'date' => array($orderRoomReport),
                );
            } else {
                array_push($orderRoomReportDatas[$orderRoomReport['roominfo_id']]['date'], $orderRoomReport);
            }
        }
        //计算每一个房间数据
        foreach ($orderRoomReportDatas as &$orderRoomReportData) {
            $tempTotalIncome = 0;
            $tempCheckIn = 0;
            $tempNotCheckIn = 0;
            $orderRoomReportData['totalRoom'] = 0;

            //根据状态计算判断是否已入住
            foreach ($orderRoomReportData['date'] as $date) {
                $tempTotalIncome += $date['price'];
                $date['status'] == 0 ? $tempNotCheckIn++ : $tempCheckIn++;
            }
            //单个房间总收入
            $orderRoomReportData['totalIncome'] = $tempTotalIncome;
            //计算平均房价
            $orderRoomReportData['price'] = $tempTotalIncome / ($tempCheckIn + $tempNotCheckIn);
            //计算入住房间总数
            $orderRoomReportData['checkIn'] = $tempCheckIn;
            //计算未入住房间总数
            $orderRoomReportData['notCheckIn'] = $tempNotCheckIn;
            //计算平均价格
            $orderRoomReportData['price'] = $orderRoomReportData['totalIncome'] / ($orderRoomReportData['checkIn'] + $orderRoomReportData['notCheckIn']);
            //房间名
            $orderRoomReportData['name'] = $roomInfos[$orderRoomReportData['roominfo_id']]['name'];
            //计算每个房间入住率
            $orderRoomReportData['occupancyRate'] = number_format(($orderRoomReportData['checkIn'] / $roomInfos[$orderRoomReportData['roominfo_id']]['canCheckinDays']) * 100, 2,'.','') . "%";
            //计算没有卖出的
            $orderRoomReportData['notSold'] = $roomInfos[$orderRoomReportData['roominfo_id']]['canCheckinDays'] - ($orderRoomReportData['checkIn'] + $orderRoomReportData['notCheckIn']);
        }
        unset($orderRoomReportData);
        $data = array();
        //数据转化
        foreach ($roomInfos as $roomInfo) {
            if (isset($data[$roomInfo['roomtype_id']])) {
                array_push($data[$roomInfo['roomtype_id']]['rooms'], $roomInfo);
            } else {
                $data[$roomInfo['roomtype_id']] = array(
                    'roomtype_id' => $roomInfo['roomtype_id'],
                    'rooms' => array($roomInfo),
                );
            }
        }
        unset($roomInfo);
        $return = array();
        //查询数据
        $totalNotCheckIn = 0;
        $totalCheckIn = 0;
        $totalPrice = 0;
        //计算每个房间总数
        foreach ($orderRoomReportDatas as $orderRoomReportDataRow) {
            $totalNotCheckIn+= $orderRoomReportDataRow['notCheckIn'];
            $totalCheckIn+= $orderRoomReportDataRow['checkIn'];
            $totalPrice+= $orderRoomReportDataRow['totalIncome'];
        }

        // 获取所有房型信息,包括删除
        $roomTypeInfo = $roomTypeModel->getInfoByHotel($hotelId, true);
        $roomTypeInfo = getArrayValueAsIndex($roomTypeInfo, 'id');

        //计算每一种房型的数据情况
        foreach ($data as &$roomTypeRow) {
            $roomTypeRow['name'] = $roomTypeInfo[$roomTypeRow['roomtype_id']]['name'];
            $roomTypeRow['isdelete'] = $roomTypeInfo[$roomTypeRow['roomtype_id']]['isdelete'];
            $RoomTypeTotalPrice = 0;
            $RoomTypeTotalCheckIn = 0;
            $RoomTypeTotalNotCheckIn = 0;
            foreach ($roomTypeRow['rooms'] as &$room) {
                $room['total'] = 0;
                $room['actualOccupancy'] = 0;
                $room['occupancyRate'] = 0;
                $room['price'] = 0;
                $room['notCheckIn'] = 0;
                $room['notSold'] = $roomInfos[$room['id']]['canCheckinDays'];

                if (isset($orderRoomReportDatas[$room['id']])) {
                    $orderRoomReportDataInfo = $orderRoomReportDatas[$room['id']];

                    $RoomTypeTotalPrice+= $orderRoomReportDataInfo['totalIncome'];
                    $RoomTypeTotalCheckIn += $orderRoomReportDataInfo['checkIn'];
                    $RoomTypeTotalNotCheckIn += $orderRoomReportDataInfo['notCheckIn'];
                    
                    $room['total'] = number_format($orderRoomReportDataInfo['totalIncome'],2,'.','');
                    $room['actualOccupancy'] = $orderRoomReportDataInfo['checkIn'];
                    $room['occupancyRate'] = $orderRoomReportDataInfo['occupancyRate'];
                    $room['price'] = number_format($orderRoomReportDataInfo['price'],2,'.','');
                    $room['notSold'] = $orderRoomReportDataInfo['notSold'] < 0 ? 0 : $orderRoomReportDataInfo['notSold'];
                    $room['notCheckIn'] = $orderRoomReportDataInfo['notCheckIn'];
                }
            }
            //计算房型总收入
            $roomTypeRow['total'] = number_format($RoomTypeTotalPrice, 2,'.','');
            //计算房型入住率
            $roomTypeRow['occupancyRate'] = number_format(($RoomTypeTotalCheckIn / $roomTypeCanCheckinDays[$roomTypeRow['roomtype_id']]) * 100, 2,'.','');
            //计算房型平均价格
            $roomTypeRow['price'] = number_format($RoomTypeTotalPrice / ($RoomTypeTotalCheckIn + $RoomTypeTotalNotCheckIn), 2,'.','');
            $roomTypeRow['price'] = $roomTypeRow['price'] ? $roomTypeRow['price'] : 0;
        }

        $return['actualOccupancy'] = $totalCheckIn;
        $return['notCheckIn'] = $totalNotCheckIn;
        $return['notSold'] = $totalCanCheckinRoomCount - ($totalCheckIn + $totalNotCheckIn);
        $return['notSold'] = $return['notSold'] < 0 ? 0 : $return['notSold'];
        $return['occupancyRate'] = number_format(($totalCheckIn / ($totalCanCheckinRoomCount)) * 100,2,'.','');
        $return['price'] = $totalPrice / ($totalCheckIn + $totalNotCheckIn);
        $return['price'] = $return['price'] ? number_format($return['price'],2,'.','') : 0;
        $return['roomInfo'] = array_values($data);


        //计算每一天的收入income
        //计算每一天的入住actualOccupancy
        //计算每一天的入住率occupancyRate
        //计算每一天的平均价格price
        //计算每一天的未售出数量notSold
        //计算每一天的未入住数量notCheckIn
        $reutrn['incomeSeries'] = $return['actualOccupancySeries'] = $return['occupancyRateSeries'] = $return['priceSeries'] = $return['notSoldSeries'] = $return['notCheckInSeries'] = array();
        //计算每一天的房间总数
        //循环比较两者数据
        
        $orderRoomReportNewDatas = array();
        foreach ($orderRoomReports as $rows) {
            if (isset($orderRoomReportNewDatas[$rows['date']])) {
                array_push($orderRoomReportNewDatas[$rows['date']]['orders'], $rows);
            } else {
                $orderRoomReportNewDatas[$rows['date']] = array(
                    'date' => $rows['date'],
                    'orders' => array($rows),
                );
            }
        }
        //计算每一天的数据
        foreach ($orderRoomReportNewDatas as &$orderRoomReportNewData) {
            $dayTotalPrice = 0;
            $dayCheckIn = 0;
            $dayNotCheckIn = 0;
            foreach ($orderRoomReportNewData['orders'] as $order) {
                $dayTotalPrice+= $order['price'];
                if ($order['status'] == 0) {
                    $dayNotCheckIn++;
                } else {
                    $dayCheckIn++;
                }
            }
            $orderRoomReportNewData['totalPrice'] = $dayTotalPrice;
            $orderRoomReportNewData['checkIn'] = $dayCheckIn;
            $orderRoomReportNewData['notCheckIn'] = $dayNotCheckIn;
            $orderRoomReportNewData['roomTotal'] = 0;
        }
        // 根据每种房型可入住天数,算出查询的每个日期的可入住房间数目
        foreach ($roomInfos as $roomInfo) {
            $roomInfoStartDate = substr($roomInfo['starttime'], 0, 10);
            $roomInfoStartDate = isBeforeTime($roomInfoStartDate, $startDate, true) ? $startDate : $roomInfoStartDate;
            for ($counter = 0 ; $counter < (int)$roomInfo['canCheckinDays']; $counter++) { 
                if (isset($orderRoomReportNewDatas[$roomInfoStartDate])) {
                    $orderRoomReportNewDatas[$roomInfoStartDate]['roomTotal']++;
                } else {
                    $orderRoomReportNewDatas[$roomInfoStartDate] = array(
                        'date' => $roomInfoStartDate,
                        'orders' => array(),
                        'totalPrice' => 0,
                        'checkIn' => 0,
                        'notCheckIn' => 0,
                        'roomTotal' => 1,
                    );
                }
                $roomInfoStartDate = date('Y-m-d', strtotime($roomInfoStartDate . ' +1 days'));
            }
        }
        unset($roomInfo);
        //  比较每一天的数据
        $dateArray = array_column($orderRoomReportNewDatas, "date");
        $dateIndex = $startDate;
        for ($i = 0; $i < ceil((strtotime($endDateEnd) - strtotime($startDate)) / 86400); $i++) {
            if (in_array($dateIndex, $dateArray)) {
                //$return['incomeSeries'][] = $orderRoomReportNewDatas[$dateIndex]['orders']['0']['receipt'] ? $orderRoomReportNewDatas[$dateIndex]['orders']['0']['receipt'] : 0;
                $return['incomeSeries'][] = $incomeDateReports[strtotime($dateIndex)];
                $return['actualOccupancySeries'][] = $orderRoomReportNewDatas[$dateIndex]['checkIn'];
                $return['occupancyRateSeries'][] = number_format(($orderRoomReportNewDatas[$dateIndex]['checkIn'] / $orderRoomReportNewDatas[$dateIndex]['roomTotal'] * 100), 3,'.','');
                $priceSeriesDivide = ($orderRoomReportNewDatas[$dateIndex]['checkIn'] + $orderRoomReportNewDatas[$dateIndex]['notCheckIn']);
                $return['priceSeries'][] = $priceSeriesDivide == 0 ? 0 : number_format($orderRoomReportNewDatas[$dateIndex]['totalPrice'] / $priceSeriesDivide, 3,'.','');
                $notSoldSeries = $orderRoomReportNewDatas[$dateIndex]['roomTotal'] - ($orderRoomReportNewDatas[$dateIndex]['checkIn'] + $orderRoomReportNewDatas[$dateIndex]['notCheckIn']);
                $return['notSoldSeries'][] = $notSoldSeries < 0 ? 0 : $notSoldSeries;
                $return['notCheckInSeries'][] = $orderRoomReportNewDatas[$dateIndex]['notCheckIn'];
            } else {
                $return['incomeSeries'][] = '0';
                $return['actualOccupancySeries'][] = '0';
                $return['occupancyRateSeries'][] = '0';
                $return['priceSeries'][] = '0';
                $return['notCheckInSeries'][] = '0';
                // 未来时间,未售出房间数
                $return['notSoldSeries'][] = $currentRoomTotal;
            }
            $dateIndex = date('Y-m-d', strtotime($dateIndex . '+1 days'));
        }
        return $return;
    }

    /**
     * 实时查询当天收入情况
     * @modify songanwei 2016-01-26
     * @param integer $hotelId 可榨ID
     * @param date $date 查询日期
     * @return type
     */
    public function getTodaySummary($hotelId, $date) {
        return $this->__singleGet('_getTodaySummary', array($hotelId, $date));
    }
    public function _getTodaySummary($hotelId, $date) {
        $orderPayRecordModel = D('OrderPayRecord');
        $orderPayRecords = $orderPayRecordModel->getInfosByHotelDate($hotelId, $date);

        // 检查操作者是否子管理员,若是,需要根据房间权限过滤父订单
        if (MODULE_NAME != 'Extend' && !empty($orderPayRecords)) {
            // 获取房间权限权限
            $adminId = getUserId();
            $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
            if (!$adminAuthorityLogic->checkIsAdmin($adminId, $hotelId)) {
                $accountLogic = A('Common/Account', 'Logic');
                $roomAuthority = $accountLogic->getAdminRoomAuthority($adminId, $hotelId);

                if (empty($roomAuthority)) {
                    $orderPayRecords = array();
                } else {
                    // 删除无房间权限的父订单的收款记录
                    $orderIds = array_column($orderPayRecords, 'orderinfo_id');
                    $orderRoomModel = D('OrderRoom');
                    $orderRooms = $orderRoomModel->getInfoByOrder($orderIds);
                    // 过滤出有权限的子订单,再过滤出有权限的父订单
                    $orderRooms = fliterArrayByKey($orderRooms, 'roominfo_id', $roomAuthority);
                    $orderIds = array_column($orderRooms, 'orderinfo_id');
                    $orderPayRecords = fliterArrayByKey($orderPayRecords, 'orderinfo_id', $orderIds);
                }
            }
        }

        $orderRoomModel = D('OrderRoom');
        $orderRooms = $orderRoomModel->getInfoByOrder(array_column($orderPayRecords, 'orderinfo_id'));
        $orderRooms = getArrayValueAsIndex($orderRooms,'orderinfo_id');
        $receipt = $refund = $deposit = $refundDeposit = 0;
        //计算数据||type=0 收款  1= 押金 2=退款 3=退押金 168=以上是其他消费
        foreach ($orderPayRecords as $orderPayRecord) {
            if ($orderRooms[$orderPayRecord['orderinfo_id']]['hour'] > 0 || $orderRooms[$orderPayRecord['orderinfo_id']]['month'] > 0) {
                continue;
            }
            switch ($orderPayRecord['type']) {
                case PAY_CHANGE_RECEIPT:// 收款
                    $receipt += (double)$orderPayRecord['pay'];
                    break;
                case PAY_CHANGE_DEPOSIT:// 收押金
                    $deposit += (double)$orderPayRecord['pay'];
                    break;
                case PAY_CHANGE_REFUND:// 退款
                    $refund += (double)$orderPayRecord['pay'];
                    break;
                case PAY_CHANGE_DEPOSIT_BACK:// 退押金
                    $refundDeposit += (double)$orderPayRecord['pay'];
                    break;
                default;
                    // 其他消费 不包括待收款
                    if ($orderPayRecord['hotelpay_id'] != 0 && !in_array($orderPayRecord['type'], [0,1,2,3])) {
                        $receipt += (double)$orderPayRecord['pay'];
                    }
                    break;
            }
        }

        //返回当天金额数据
        $data = array(
            'receipt' => $receipt,
            'deposit' => $deposit,
            'refund' => $refund,
            'refundDeposit' => $refundDeposit
        );
        return $data;
    }

    /**
     * 实时查询房间运营信息
     * @modify trainyao 2016-09-30 创建
     * @param  integer   $hotelId   客栈ID
     * @param  string   $date      需要实时查询
     * @return array              {roomTotal(房间总数), sold(已售出房间数), notSold(未售出房间数), occupancy(已入住订单数), checkInCount(已入住订单数), notCheckIn(未入住订单数), price(平均价格), occupancyRate(入住率)}
     */
    public function getTodayRoomReport($hotelId, $date) {
        return $this->__singleGet('_getTodayRoomReport', array($hotelId, $date));
    }
    protected function _getTodayRoomReport($hotelId, $date) {
        //计算房间总数
        $roomLogic = A('Common/Room', 'Logic');
        $roomInfos = $roomLogic->getCanCheckinRoomByDate($hotelId, date('Y-m-d') . ' 00:00:00', date('Y-m-d') . ' 23:59:59');
        // 检查操作者是否子管理员,若是,需要根据房间权限过滤房间数据
        if (MODULE_NAME != 'Extend') {
            // 获取房间权限权限
            $adminId = getUserId();
            $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
            $needFilterRoom = false;
            if (!$adminAuthorityLogic->checkIsAdmin($adminId, $hotelId)) {
                $needFilterRoom = true;
                $accountLogic = A('Common/Account', 'Logic');
                $roomAuthority = $accountLogic->getAdminRoomAuthority($adminId, $hotelId);

                $roomInfos = fliterArrayByKey($roomInfos, 'id', $roomAuthority);
            }
        }
        // 算出房间在时间段内真正能卖的房间
        $roomTotal = 0;
        foreach ($roomInfos as $roomInfoItem) {
            $roomTotal += $roomInfoItem['canCheckinDays'];
        }
        unset($roomInfoItem);
        $data = array();
        $data['roomTotal'] = $roomTotal;
        $notSold = $roomTotal;
        $occupancy = $notCheckIn = $sold = $price = 0;
        $orderRoomModel = D('OrderRoom');
        $orderRooms = $orderRoomModel->getInfoByHotelDay($hotelId, $date);
        // 对凌晨订单处理
        $midnightOrderRooms = $orderRoomModel->getMidnightOrder($hotelId, $date);
        if (!empty($midnightOrderRooms)) {
            $orderRooms = getArrayValueAsIndex($orderRooms, 'id');
            // 去除重复
            foreach ($midnightOrderRooms as $key => $midnightOrderRoomItem) {
                if (isset($orderRooms[$midnightOrderRoomItem['id']])) {
                    unset($midnightOrderRooms[$key]);
                }
            }
            unset($midnightOrderRoomItem);
        }
        $orderRooms = array_merge($orderRooms, $midnightOrderRooms);

        // 检查操作者是否子管理员,若是,需要根据房间权限过滤房间数据
        if (MODULE_NAME != 'Extend' && $needFilterRoom) {
            $orderRooms = fliterArrayByKey($orderRooms, 'roominfo_id', $roomAuthority);
        }

        foreach ($orderRooms as $orderRoom) {
            switch ($orderRoom['status']) {
                case '1':
                    //表示已经出售但是还没有来住
                    $notCheckIn++;
                    $notSold--;
                    $sold++;
                    $price+= round(($orderRoom['payment'] / $orderRoom['night']), 2);
                    break;
                case '2':
                    $notSold--;
                    $sold++;
                    $occupancy++;
                    $price+= round(($orderRoom['payment'] / $orderRoom['night']), 2);
                    break;
                case '3':
                    $notSold--;
                    $sold++;
                    $occupancy++;
                    $price+= round(($orderRoom['payment'] / $orderRoom['night']), 2);
                    break;
                case '4':
                    break;
                default :
                    break;
            }
        }
        $data['sold'] = $sold;
        $data['notSold'] = $notSold;
        $data['occupancy'] = $occupancy;
        $data['checkInCount'] = $occupancy;
        $data['notCheckIn'] = $notCheckIn;
        $data['price'] = empty($price) ? 0 : round(($price / $sold), 2);
        $data['occupancyRate'] = $occupancy / count($roomInfos);
        return $data;
    }

    /**
     * 计算当天的订单房间情况
     * @modify songanwei 2016-01-26
     * @param integer $hotelId 客栈ID
     * @param date $date  date('Y-m-d')
     * @return type
     */
    public function getTodayRoomDetail($hotelId, $date) {
        $orderRoomModel = D('OrderRoom');
        $data = array();
        $orderRooms = $orderRoomModel->getInfoByHotelDay($hotelId, $date);
        //数据转化并进行分组
        $data = array();
        foreach ($orderRooms as $orderRoom) {
            switch ($orderRoom['status']) {
                case '1':
                    $data[] = array(
                        'hotelentity_id' => $orderRoom['hotelentity_id'],
                        'date' => $date,
                        'roominfo_id' => $orderRoom['roominfo_id'],
                        'price' => floatval($orderRoom['payment']) / $orderRoom['night'],
                        'status' => 0,
                        'orderroom_id' => $orderRoom['id']
                    );
                    break;
                case '2':
                    $data[] = array(
                        'hotelentity_id' => $orderRoom['hotelentity_id'],
                        'date' => $date,
                        'roominfo_id' => $orderRoom['roominfo_id'],
                        'price' => floatval($orderRoom['payment']) / $orderRoom['night'],
                        'status' => 1,
                        'orderroom_id' => $orderRoom['id']
                    );
                    break;
                case '3':
                    $data[] = array(
                        'hotelentity_id' => $orderRoom['hotelentity_id'],
                        'date' => $date,
                        'roominfo_id' => $orderRoom['roominfo_id'],
                        'price' => floatval($orderRoom['payment']) / $orderRoom['night'],
                        'status' => 1,
                        'orderroom_id' => $orderRoom['id']
                    );
                    break;
                case '4':
                    break;
            }
        }
        //计算同一天的房间数据分组
        return $data;
    }

    /**
     * 计算当天的订单房间情况
     * @modify zhangzhen 2017-06-06
     * @param integer $hotelId 客栈ID
     * @param date $date  date('Y-m-d')
     * @return type
     */
    public function getTodayHourRoomDetail($hotelId, $date) {
        $orderRoomModel = D('OrderRoom');
        $data = array();
        $orderRooms = $orderRoomModel->getInfoByHotelHour($hotelId, $date);
        //数据转化并进行分组
        $data = array();
        foreach ($orderRooms as $orderRoom) {
            switch ($orderRoom['status']) {
                case '1':
                    $data[] = array(
                        'hotelentity_id' => $orderRoom['hotelentity_id'],
                        'date' => $date,
                        'roominfo_id' => $orderRoom['roominfo_id'],
                        'price' => $orderRoom['payment'],
                        'status' => 0,
                        'orderroom_id' => $orderRoom['id']
                    );
                    break;
                case '2':
                    $data[] = array(
                        'hotelentity_id' => $orderRoom['hotelentity_id'],
                        'date' => $date,
                        'roominfo_id' => $orderRoom['roominfo_id'],
                        'price' => $orderRoom['payment'],
                        'status' => 1,
                        'orderroom_id' => $orderRoom['id']
                    );
                    break;
                case '3':
                    $data[] = array(
                        'hotelentity_id' => $orderRoom['hotelentity_id'],
                        'date' => $date,
                        'roominfo_id' => $orderRoom['roominfo_id'],
                        'price' => $orderRoom['payment'],
                        'status' => 1,
                        'orderroom_id' => $orderRoom['id']
                    );
                    break;
                case '4':
                    break;
            }
        }
        //计算同一天的房间数据分组
        return $data;
    }

    /**
     * 计算当天的订单房间情况
     * @modify zhangzhen 2017-08-14
     * @param integer $hotelId 客栈ID
     * @param date $date  date('Y-m-d')
     * @return type
     */
    public function getTodayMonthRoomDetail($hotelId, $date) {
        $orderRoomModel = D('OrderRoom');
        $data = array();
        $orderRooms = $orderRoomModel->getInfoByHotelMonth($hotelId, $date);
        //数据转化并进行分组
        $data = array();
        foreach ($orderRooms as $orderRoom) {
            switch ($orderRoom['status']) {
                case '1':
                    $data[] = array(
                        'hotelentity_id' => $orderRoom['hotelentity_id'],
                        'date' => $date,
                        'roominfo_id' => $orderRoom['roominfo_id'],
                        'price' => floatval($orderRoom['payment']) / $orderRoom['night'],
                        'status' => 0,
                        'orderroom_id' => $orderRoom['id']
                    );
                    break;
                case '2':
                    $data[] = array(
                        'hotelentity_id' => $orderRoom['hotelentity_id'],
                        'date' => $date,
                        'roominfo_id' => $orderRoom['roominfo_id'],
                        'price' => floatval($orderRoom['payment']) / $orderRoom['night'],
                        'status' => 1,
                        'orderroom_id' => $orderRoom['id']
                    );
                    break;
                case '3':
                    $data[] = array(
                        'hotelentity_id' => $orderRoom['hotelentity_id'],
                        'date' => $date,
                        'roominfo_id' => $orderRoom['roominfo_id'],
                        'price' => floatval($orderRoom['payment']) / $orderRoom['night'],
                        'status' => 1,
                        'orderroom_id' => $orderRoom['id']
                    );
                    break;
                case '4':
                    break;
            }
        }
        //计算同一天的房间数据分组
        return $data;
    }

    /**
     * 返回实时查询的收入支出数据
     * @modify songanwei 2016-01-27
     * @param integer $hotelId 客栈ID
     * @param date $date  查询日期
     * @return array
     */
    public function getTodayHotelInOutComeData($hotelId, $date) {
        $orderPayRecordModel = D('OrderPayRecord');
        $orderPayRecords = $orderPayRecordModel->getInfosByHotelDate($hotelId, $date);
        $records = $data = array();
        //数据分组
        foreach ($orderPayRecords as $orderPayRecord) {
            $records[$orderPayRecord['hotelpay_id']][] = $orderPayRecord;
        }
        //分别计算没中支付方式的总和
        foreach ($records as $key => $record) {
            $data[] = array(
                'hotelpay_id' => $key,
                'records' => $record
            );
        }

        $return = array();
        //返回客栈支付数据
        foreach ($data as $hotelPay) {
            $tempIncome = $tempOutcome = 0;
            foreach ($hotelPay['records'] as $record) {
                if (($record['type'] == 0) || ($record['type'] == 1)) {
                    $tempIncome += intval($record['pay']);
                }
                if (($record['type'] == 2) || ($record['type'] == 3)) {
                    $tempOutcome += intval($record['pay']);
                }
            }
            $return[] = array(
                'hotelentity_id' => $hotelId,
                'hotelpay_id' => $hotelPay['hotelpay_id'],
                'date' => $date,
                'income' => $tempIncome,
                'outcome' => $tempOutcome
            );
        }
        return $return;
    }
    /**
     * 查询财务收支信息
     * @modify trainyao 2016-01-19 创建
     * @modify trainyao 2016-07-01 增加房间权限限制
     * @param  integer   $hotelId   客栈id
     * @param  string   $startDate 开始日期
     * @param  string      $endDate   结束日期
     * @return array              信息数组
     */
    public function getVipFinanceData($hotelId, $startDate, $endDate) {
        return $this->__singleGet('_getVipFinanceData', array($hotelId, $startDate, $endDate));
    }
    protected function _getVipFinanceData($hotelId, $startDate, $endDate = null) {
        if (is_null($endDate)) {
            $endDate = $startDate;
        }
        $endDate = $endDate.' 23:59:59';
        $count = [];
        // 获取具体支付信息记录
        $orderLogic = A('Common/Order', 'Logic');
        $orderInfoModel = D('OrderInfo');
        $orderInfos = $orderInfoModel->getInfoByHotelAndTime($hotelId, $startDate, $endDate);
        $vipUserModel = D('VipUser');
        foreach ($orderInfos as $info => $orderInfo) {
            $vipUserInfo = $vipUserModel->getJoinVipInfoByMobile($hotelId,$orderInfo['mobile'],$orderInfo['areacode']);
            if($vipUserInfo){
                $count[$vipUserInfo['vipinfo_id']]['level'] = $vipUserInfo['vipname']; 
                $count[$vipUserInfo['vipinfo_id']]['checkintotal'] += $orderInfo['checkin'];
                /*$count[$vipUserInfo['vipinfo_id']]['paytotal'] += $orderInfo['deposit'] + $orderInfo['receipt'];
                $count['paytotal'] += $orderInfo['deposit'] + $orderInfo['receipt'];*/
                $count[$vipUserInfo['vipinfo_id']]['paytotal'] += $orderInfo['receipt'];
                $count['paytotal'] += $orderInfo['receipt'];
                $count['checkintotal'] += $orderInfo['checkin'];
            }else{
                $count[0]['level'] = $this->levelMap[LANG_SET]['level'];
                $count[0]['checkintotal'] += $orderInfo['checkin'];
                /*$count[0]['paytotal'] += $orderInfo['deposit'] + $orderInfo['receipt'];
                $count['paytotal'] += $orderInfo['deposit'] + $orderInfo['receipt'];*/
                $count[0]['paytotal'] += $orderInfo['receipt'];
                $count['paytotal'] += $orderInfo['receipt'];
                $count['checkintotal'] += $orderInfo['checkin'];
            }
        }

        // 获取默认货币符号
        $currencyLogic = A('Common/Currency', 'Logic');
        $hotelDefaultCurrency = $currencyLogic->takeHotelCurrency($hotelId, true);
        $hotelDefaultSymbol = !empty($hotelDefaultCurrency) ? $hotelDefaultCurrency[0]['symbol'] : '¥';

        $checkin = [];
        $payment = [];
        foreach ($count as $key => $onecount) {
            $checkin[$key]['name'] = $onecount['level'];
            $checkin[$key]['total'] = $onecount['checkintotal']. $this->levelMap[LANG_SET]['ci'];
            $checkin[$key]['value'] = $onecount['checkintotal'] / $count['checkintotal'];
            $payment[$key]['name'] = $onecount['level'];
            $payment[$key]['total'] = $hotelDefaultSymbol . $onecount['paytotal'];
            $payment[$key]['value'] = $onecount['paytotal'] / $count['paytotal'];
        }
        unset($checkin['checkintotal']);  
        unset($checkin['paytotal']);
        unset($payment['checkintotal']);
        unset($payment['paytotal']);

        // 获取会员充值记录
        $vipUserModel = D('VipUser');
        $vipUserCardRecordModel = D('VipUserCardRecord');
        $vipUserInfo = $vipUserModel->getInfoByHotel($hotelId);
        $vipUserIds = array_column($vipUserInfo, 'id');
        $vipUserCardRecordInfo = $vipUserCardRecordModel->getVipCardRecord($vipUserIds, $startDate, $endDate, $hotelId);
        foreach ($vipUserCardRecordInfo as $key => &$vipUserCardRecordItem) {
            $vipUserCardRecordItem['updatetime'] = strtotime(substr($vipUserCardRecordItem['updatetime'], 0, 10));
        }
        unset($vipUserCardRecordItem);

        $vipUserCardRecordInfo = getArrayValueAsIndex($vipUserCardRecordInfo, 'updatetime', true);
        $IndexTime = strtotime($startDate);
        for ($i = 0; $i < ceil((strtotime($endDate) - strtotime($startDate)) / 86400); $i++) {
            if (isset($vipUserCardRecordInfo[$IndexTime])) {
                $rechargePrice = 0;
                $consumptionPrice = 0;
                foreach ($vipUserCardRecordInfo[$IndexTime] as $key => $recordItem) {
                    // 统计充值
                    if ($recordItem['change_price'] > 0) {
                        $rechargePrice += $recordItem['change_price'];
                    } else {
                        // 统计消费
                        $consumptionPrice += abs($recordItem['change_price']);
                    }
                }
                unset($recordItem);

                $rechargeData[] = $rechargePrice;
                $consumptionData[] = $consumptionPrice;
            } else {
                $rechargeData[] = 0;
                $consumptionData[] = 0;
            }

            $IndexTime += 86400;
        }

        return [
                'checkin'=>array_values($checkin),
                'payment'=>array_values($payment),
                'recharge'=>$rechargeData,
                'consumption'=>$consumptionData,
            ];
        
    }

    /**
     * 义卖金额收支信息
     * @modify wenhui 2017-09-20 创建
     * @param  integer   $hotelId   客栈id
     * @param  string   $startDate 开始日期
     * @param  string      $endDate   结束日期
     * @return array              信息数组
     */
    public function getCharityData($hotelId, $startDate, $endDate, $current) {
        return $this->__singleGet('_getCharityData', array($hotelId, $startDate, $endDate, $current));
    }
    protected function _getCharityData($hotelId, $startDate, $endDate = null, $current = 1) {
        if (is_null($endDate)) {
            $endDate = $startDate;
        }
        $endDate = $endDate.' 23:59:59';
        $count = [];
        // 获取具体支付信息记录
        $orderInfoModel = D('OrderInfo');
        $orderRoomModel = D('OrderRoom');
        $orderInfos = $orderInfoModel->getInfoByHotelAndDate($hotelId, $startDate, $endDate, ['in',[1,2,3,4]], true);

        $orderLogic = A('Common/Order', 'Logic');
        $orderStatus = $orderLogic->statusMap[LANG_SET];
        $data['totalCharity'] = 0;
        $data['order'] = [];
        if (!empty($orderInfos)) {
            foreach ($orderInfos as $key => $orderItem) {
                $orderRoomInfo = $orderRoomModel->getInfoByOrder($orderItem['id']);
                $orderNumber = encodeOrderNumber($orderRoomInfo[0]['id'], 'MZ');
                $data['totalCharity'] += $orderItem['charityprice'];
                array_push($data['order'], array(
                    'orderNumber' => $orderNumber,
                    'name' => $orderItem['name'],
                    'mobile' => '+' . $orderItem['areacode'] . ' ' . $orderItem['mobile'],
                    'receipt' => $orderItem['receipt'],
                    'charity' => $orderItem['charityprice'],
                    'orderTime' => $orderItem['createtime'],
                    'status' => $orderStatus[$orderItem['status']],
                    'sortTime' => strtotime($orderItem['createtime']),
                ));
            }
            unset($orderItem);
        }
        $data['totalCharity'] = number_format($data['totalCharity'], 2, '.', '');
        /**
         *  排序
         *  排序方式 推荐客栈按点击量  有城市搜索 按最近距离
         *  SORT_ASC - 默认，按升序排列。(A-Z)
         *  SORT_DESC - 按降序排列。(Z-A)
         *  随后可以指定排序的类型：
         *  SORT_REGULAR - 默认。将每一项按常规顺序排列。
         *  SORT_NUMERIC - 将每一项按数字顺序排列。
         *  SORT_STRING - 将每一项按字母顺序排列
         */
        if (!empty($data['order'])) {
            $data['order'] = my_sort($data['order'], 'sortTime', SORT_DESC, SORT_NUMERIC);
        }
        // 分页
        $order = createPageInfo($data['order'], $current, C('NEWS_PAGE_SIZE'));
        $data['order'] = $order['data'];
        $data['page'] = array(
            'current' => $order['current'],
            'size' => $order['size'],
            'total' => $order['total'],
            'pageTotal' => $order['pageTotal'],
        );

        return $data;
    }

     /**
     * 实时查询当天收入情况
     * @modify zhangzhen 2017-06-05
     * @param integer $hotelId 客栈ID
     * @param date $date 查询日期
     * @return \Common\Controller\mixin
      */
    public function getTodayHourSummary($hotelId, $date) {
        return $this->__singleGet('_getTodayHourSummary', array($hotelId, $date));
    }
    public function _getTodayHourSummary($hotelId, $date) {
        $orderPayRecordModel = D('OrderPayRecord');
        $orderPayRecords = $orderPayRecordModel->getInfosByHotelDate($hotelId, $date);
        // 检查操作者是否子管理员,若是,需要根据房间权限过滤父订单
        if (MODULE_NAME != 'Extend' && !empty($orderPayRecords)) {
            // 获取房间权限权限
            $adminId = getUserId();
            $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
            if (!$adminAuthorityLogic->checkIsAdmin($adminId, $hotelId)) {
                $accountLogic = A('Common/Account', 'Logic');
                $roomAuthority = $accountLogic->getAdminRoomAuthority($adminId, $hotelId);

                if (empty($roomAuthority)) {
                    $orderPayRecords = array();
                } else {
                    // 删除无房间权限的父订单的收款记录
                    $orderIds = array_column($orderPayRecords, 'orderinfo_id');
                    $orderRoomModel = D('OrderRoom');
                    $orderRooms = $orderRoomModel->getInfoByOrder($orderIds);
                    // 过滤出有权限的子订单,再过滤出有权限的父订单
                    $orderRooms = fliterArrayByKey($orderRooms, 'roominfo_id', $roomAuthority);
                    $orderIds = array_column($orderRooms, 'orderinfo_id');
                    $orderPayRecords = fliterArrayByKey($orderPayRecords, 'orderinfo_id', $orderIds);
                }
            }
        }
        $orderRoomModel = D('OrderRoom');
        $orderRooms = $orderRoomModel->getInfoByOrder(array_column($orderPayRecords, 'orderinfo_id'));
        $orderRooms = getArrayValueAsIndex($orderRooms,'orderinfo_id');

        $receipt = $refund = $deposit = $refundDeposit = 0;
        //计算数据||type=0 收款  1= 押金 2=退款 3=退押金 168=以上是其他消费
        foreach ($orderPayRecords as $orderPayRecord) {
            if ($orderRooms[$orderPayRecord['orderinfo_id']]['hour'] == 0) {
                continue;
            }
            switch ($orderPayRecord['type']) {
                case PAY_CHANGE_RECEIPT:// 收款
                    $receipt += (double)$orderPayRecord['pay'];
                    break;
                case PAY_CHANGE_DEPOSIT:// 收押金
                    $deposit += (double)$orderPayRecord['pay'];
                    break;
                case PAY_CHANGE_REFUND:// 退款
                    $refund += (double)$orderPayRecord['pay'];
                    break;
                case PAY_CHANGE_DEPOSIT_BACK:// 退押金
                    $refundDeposit += (double)$orderPayRecord['pay'];
                    break;
                default;
                    // 其他消费 不包括待收款
                    if ($orderPayRecord['hotelpay_id'] != 0 && !in_array($orderPayRecord['type'], [0,1,2,3])) {
                        $receipt += (double)$orderPayRecord['pay'];
                    }
                    break;
            }
        }

        //返回当天金额数据
        $data = array(
            'receipt' => $receipt,
            'deposit' => $deposit,
            'refund' => $refund,
            'refundDeposit' => $refundDeposit
        );
        return $data;
    }

    /**
     * 实时查询当天收入情况
     * @modify zhangzhen 2017-06-05
     * @param integer $hotelId 客栈ID
     * @param date $date 查询日期
     * @return type
     */
    public function getTodayMonthSummary($hotelId, $date) {
        return $this->__singleGet('_getTodayMonthSummary', array($hotelId, $date));
    }
    public function _getTodayMonthSummary($hotelId, $date) {
        $orderPayRecordModel = D('OrderPayRecord');
        $orderPayRecords = $orderPayRecordModel->getInfosByHotelDate($hotelId, $date);
        // 检查操作者是否子管理员,若是,需要根据房间权限过滤父订单
        if (MODULE_NAME != 'Extend' && !empty($orderPayRecords)) {
            // 获取房间权限权限
            $adminId = getUserId();
            $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
            if (!$adminAuthorityLogic->checkIsAdmin($adminId, $hotelId)) {
                $accountLogic = A('Common/Account', 'Logic');
                $roomAuthority = $accountLogic->getAdminRoomAuthority($adminId, $hotelId);

                if (empty($roomAuthority)) {
                    $orderPayRecords = array();
                } else {
                    // 删除无房间权限的父订单的收款记录
                    $orderIds = array_column($orderPayRecords, 'orderinfo_id');
                    $orderRoomModel = D('OrderRoom');
                    $orderRooms = $orderRoomModel->getInfoByOrder($orderIds);
                    // 过滤出有权限的子订单,再过滤出有权限的父订单
                    $orderRooms = fliterArrayByKey($orderRooms, 'roominfo_id', $roomAuthority);
                    $orderIds = array_column($orderRooms, 'orderinfo_id');
                    $orderPayRecords = fliterArrayByKey($orderPayRecords, 'orderinfo_id', $orderIds);
                }
            }
        }
        $orderRoomModel = D('OrderRoom');
        $orderRooms = $orderRoomModel->getInfoByOrder(array_column($orderPayRecords, 'orderinfo_id'));
        $orderRooms = getArrayValueAsIndex($orderRooms,'orderinfo_id');

        $receipt = $refund = $deposit = $refundDeposit = 0;
        //计算数据||type=0 收款  1= 押金 2=退款 3=退押金 168=以上是其他消费
        foreach ($orderPayRecords as $orderPayRecord) {
            if ($orderRooms[$orderPayRecord['orderinfo_id']]['month'] == 0 ) {
                continue;
            }
            switch ($orderPayRecord['type']) {
                case PAY_CHANGE_RECEIPT:// 收款
                    $receipt += (double)$orderPayRecord['pay'];
                    break;
                case PAY_CHANGE_DEPOSIT:// 收押金
                    $deposit += (double)$orderPayRecord['pay'];
                    break;
                case PAY_CHANGE_REFUND:// 退款
                    $refund += (double)$orderPayRecord['pay'];
                    break;
                case PAY_CHANGE_DEPOSIT_BACK:// 退押金
                    $refundDeposit += (double)$orderPayRecord['pay'];
                    break;
                default;
                    // 其他消费 不包括待收款
                    if ($orderPayRecord['hotelpay_id'] != 0 && !in_array($orderPayRecord['type'], [0,1,2,3])) {
                        $receipt += (double)$orderPayRecord['pay'];
                    }
                    break;
            }
        }

        //返回当天金额数据
        $data = array(
            'receipt' => $receipt,
            'deposit' => $deposit,
            'refund' => $refund,
            'refundDeposit' => $refundDeposit
        );
        return $data;
    }
    /**
     * 实时查询房间运营信息
     * @modify trainyao 2016-09-30 创建
     * @param  integer   $hotelId   客栈ID
     * @param  string   $date      需要实时查询
     * @return array              {roomTotal(房间总数), sold(已售出房间数), notSold(未售出房间数), occupancy(已入住订单数), checkInCount(已入住订单数), notCheckIn(未入住订单数), price(平均价格), occupancyRate(入住率)}
     */
    public function getTodayHourRoomReport($hotelId, $date) {
        return $this->__singleGet('_getTodayHourRoomReport', array($hotelId, $date));
    }
    protected function _getTodayHourRoomReport($hotelId, $date) {
        //计算房间总数
        $roomLogic = A('Common/Room', 'Logic');
        $roomInfos = $roomLogic->getCanCheckinRoomByDate($hotelId, $date . ' 00:00:00', $date . ' 23:59:59');
        // 检查操作者是否子管理员,若是,需要根据房间权限过滤房间数据
        if (MODULE_NAME != 'Extend') {
            // 获取房间权限权限
            $adminId = getUserId();
            $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
            $needFilterRoom = false;
            if (!$adminAuthorityLogic->checkIsAdmin($adminId, $hotelId)) {
                $needFilterRoom = true;
                $accountLogic = A('Common/Account', 'Logic');
                $roomAuthority = $accountLogic->getAdminRoomAuthority($adminId, $hotelId);

                $roomInfos = fliterArrayByKey($roomInfos, 'id', $roomAuthority);
            }
        }
        $hourRoomModel = D('HourRoom');
        $hourRooms = $hourRoomModel->getInfosByHotel($hotelId);
        $hourRoomIds = array_column($hourRooms,'roominfo_id');
        // 算出房间在时间段内真正能卖的房间
        $roomTotal = 0;
        foreach ($roomInfos as $roomInfoItem) {
            if (in_array($roomInfoItem['id'], $hourRoomIds)) {
                $roomTotal += $roomInfoItem['canCheckinDays'];
            }
        }
        unset($roomInfoItem);
        $data = array();
        $data['roomTotal'] = $roomTotal;
        $notSold = $roomTotal;
        $occupancy = $notCheckIn = $sold = $price = $rest = 0;
        $orderRoomModel = D('OrderRoom');
        $orderRooms = $orderRoomModel->getInfoByHotelHour($hotelId, $date);
        // 检查操作者是否子管理员,若是,需要根据房间权限过滤房间数据
        if (MODULE_NAME != 'Extend' && $needFilterRoom) {
            $orderRooms = fliterArrayByKey($orderRooms, 'roominfo_id', $roomAuthority);
        }
        $roomSoldFlag = [];
        $roomIds = [];
        foreach ($orderRooms as $orderRoom) {
            if (! in_array($orderRoom['roominfo_id'], $roomIds)){
                array_push($roomIds, $orderRoom['roominfo_id']);
                if($orderRoom['status'] == 1 || $orderRoom['status'] == 2){
                    $rest++;
                }
            }  
            switch ($orderRoom['status']) {
                case '1':
                    //表示已经出售但是还没有来住
                    $notCheckIn++;
                    $notSold--;
                    $sold++;
                    $price+= $orderRoom['payment'];
                    break;
                case '2':
                    $notSold--;
                    $sold++;
                    $occupancy++;
                    $price+= $orderRoom['payment'];
                    break;
                case '3':
                    $notSold--;
                    $sold++;
                    $occupancy++;
                    $price+= $orderRoom['payment'];
                    break;
                case '4':
                    break;
                default :
                    break;
            }
        }
        $data['sold'] = $sold;
        $data['rest'] = $rest;
        $data['notSold'] = $notSold < 0 ? 0 : $notSold;
        $data['occupancy'] = $occupancy;
        $data['checkInCount'] = $occupancy;
        $data['notCheckIn'] = $notCheckIn;
        $data['price'] = empty($price) ? 0 : round(($price / $sold), 2);
        $data['occupancyRate'] = $occupancy / count($hourRoomIds);
        return $data;
    }

    /**
     * 实时查询房间运营信息
     * @modify trainyao 2016-09-30 创建
     * @param  integer   $hotelId   客栈ID
     * @param  string   $date      需要实时查询
     * @return array              {roomTotal(房间总数), sold(已售出房间数), notSold(未售出房间数), occupancy(已入住订单数), checkInCount(已入住订单数), notCheckIn(未入住订单数), price(平均价格), occupancyRate(入住率)}
     */
    public function getTodayMonthRoomReport($hotelId, $date) {
        return $this->__singleGet('_getTodayMonthRoomReport', array($hotelId, $date));
    }
    protected function _getTodayMonthRoomReport($hotelId, $date) {
        //计算房间总数
        $roomLogic = A('Common/Room', 'Logic');
        $roomInfos = $roomLogic->getCanCheckinRoomByDate($hotelId, date('Y-m-d') . ' 00:00:00', date('Y-m-d') . ' 23:59:59');
        // 检查操作者是否子管理员,若是,需要根据房间权限过滤房间数据
        if (MODULE_NAME != 'Extend') {
            // 获取房间权限权限
            $adminId = getUserId();
            $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
            $needFilterRoom = false;
            if (!$adminAuthorityLogic->checkIsAdmin($adminId, $hotelId)) {
                $needFilterRoom = true;
                $accountLogic = A('Common/Account', 'Logic');
                $roomAuthority = $accountLogic->getAdminRoomAuthority($adminId, $hotelId);

                $roomInfos = fliterArrayByKey($roomInfos, 'id', $roomAuthority);
            }
        }
        $longRoomModel = D('LongRoom');
        $longRooms = $longRoomModel->getInfosByHotel($hotelId);
        $longRoomIds = array_column($longRooms,'roominfo_id');
        // 算出房间在时间段内真正能卖的房间
        $roomTotal = 0;
        foreach ($roomInfos as $roomInfoItem) {
            if (in_array($roomInfoItem['id'], $longRoomIds)) {
                $roomTotal += $roomInfoItem['canCheckinDays'];
            }
        }
        unset($roomInfoItem);
        $data = array();
        $data['roomTotal'] = $roomTotal;
        $notSold = $roomTotal;
        $occupancy = $notCheckIn = $sold = $price = $rest = 0;
        $orderRoomModel = D('OrderRoom');
        $orderRooms = $orderRoomModel->getInfoByHotelMonth($hotelId, $date);
        // 检查操作者是否子管理员,若是,需要根据房间权限过滤房间数据
        if (MODULE_NAME != 'Extend' && $needFilterRoom) {
            $orderRooms = fliterArrayByKey($orderRooms, 'roominfo_id', $roomAuthority);
        }
        $roomIds = [];
        foreach ($orderRooms as $orderRoom) {
            if (! in_array($orderRoom['roominfo_id'], $roomIds)){
                array_push($roomIds, $orderRoom['roominfo_id']);
                if($orderRoom['status'] == 1 || $orderRoom['status'] == 2){
                    $rest++;
                }
            }
            switch ($orderRoom['status']) {
                case '1':
                    //表示已经出售但是还没有来住
                    $notCheckIn++;
                    $notSold--;
                    $sold++;
                    $price+= $orderRoom['payment'];
                    break;
                case '2':
                    $notSold--;
                    $sold++;
                    $occupancy++;
                    $price+= $orderRoom['payment'];
                    break;
                case '3':
                    $notSold--;
                    $sold++;
                    $occupancy++;
                    $price+= $orderRoom['payment'];
                    break;
                case '4':
                    break;
                default :
                    break;
            }
        }
        $data['sold'] = $sold;
        $data['rest'] = $rest;
        $data['notSold'] = $notSold < 0 ? 0 : $notSold;
        $data['occupancy'] = $occupancy;
        $data['checkInCount'] = $occupancy;
        $data['notCheckIn'] = $notCheckIn;
        $data['price'] = empty($price) ? 0 : round(($price / $sold), 2);
        $data['occupancyRate'] = $occupancy / count($longRoomIds);
        return $data;
    }

    /**
     * [getBucketReport description]
     * @param $hotelId
     * @param $startDate
     * @param $endDate
     * @param $type
     * @return array [type]            [description]
     */
    public function getBucketReport($hotelId, $startDate, $endDate, $type) {
        //计算房间总数
        $roomLogic = A('Common/Room', 'Logic');
        $roomInfos = $roomLogic->getCanCheckinRoomByDate($hotelId, $startDate . ' 00:00:00', $endDate . ' 23:59:59');
        // 检查操作者是否子管理员,若是,需要根据房间权限过滤房间数据
        if (MODULE_NAME != 'Extend') {
            // 获取房间权限权限
            $adminId = getUserId();
            $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
            $needFilterRoom = false;
            if (!$adminAuthorityLogic->checkIsAdmin($adminId, $hotelId)) {
                $needFilterRoom = true;
                $accountLogic = A('Common/Account', 'Logic');
                $roomAuthority = $accountLogic->getAdminRoomAuthority($adminId, $hotelId);

                $roomInfos = fliterArrayByKey($roomInfos, 'id', $roomAuthority);
            }
        }
        if ($type == 2 || $type == 0) {
            $hourRoomModel = D('HourRoom');
            $hourRooms = $hourRoomModel->getInfosByHotel($hotelId);
            $hourRoomIds = array_column($hourRooms,'roominfo_id');
        }
        // 算出房间在时间段内真正能卖的房间
        $roomTotal = 0;
        if ($type == 2 || $type == 0) {
            $hourRoomInfos = $roomInfos;
            foreach ($hourRoomInfos as $key => $roomInfoItem) {
                if (!in_array($roomInfoItem['id'], $hourRoomIds)) {
                    unset($hourRoomInfos[$key]);
                }
            }
            $hourRoomInfos = array_values($hourRoomInfos);
        }
        unset($roomInfoItem);
        
        $data = array();
        $orderRoomModel = D('OrderRoom');
        $startTime = strtotime($startDate);
        $endTime = strtotime($endDate);
        $orderRooms = [];
        $income = 0;
        $outcome = 0;
        $detail = [];
        $hourRoom = [];
        $normalRoom = [];
        
        // 多语言判断
        $lang = LANG_SET;
        $lang = isset($lang) ? $lang : 'en_us';
        switch ($lang) {
            case 'zh_cn':
                $weekArray = array("周日", "周一", "周二", "周三", "周四", "周五", "周六");
                break;
            case 'zh_tw':
                $weekArray = array("週日", "週一", "週二", "週三", "週四", "週五", "週六");
                break;
            default:
                $weekArray = array("Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat");
                break;
        }
        
        for ($i = $startTime ; $i <= $endTime; $i+=86400) { 
            $dateIndex = date('Y-m-d', $i);
             if ($type == 1 || $type == 0) {
                $tempSummmary = $this->getTodaySummary($hotelId, $dateIndex);
                $income += $tempIncome = $tempSummmary['receipt'] + $tempSummmary['deposit'];
                $outcome += $tempOutcome = $tempSummmary['refund'] + $tempSummmary['refundDeposit'];
                $temp = $orderRoomModel->getInfoByHotelDay($hotelId, $dateIndex);
                $orderRooms = array_merge($orderRooms, $temp);
                $normalRoom['income'] += $tempIncome;
                $normalRoom['outcome'] += $tempOutcome;
                $normalRoom['surplus']= $normalRoom['income'] - $normalRoom['outcome'];
            } 
            if ($type == 2 || $type == 0) {
                $tempSummmary = $this->getTodayHourSummary($hotelId, $dateIndex);
                $income += $tempIncome = $tempSummmary['receipt'] + $tempSummmary['deposit'];
                $outcome += $tempOutcome = $tempSummmary['refund'] + $tempSummmary['refundDeposit'];
                $temp = $orderRoomModel->getInfoByHotelHour($hotelId, $dateIndex);
                $orderRooms = array_merge($orderRooms, $temp);
                $hourRoom['income'] += $tempIncome;
                $hourRoom['outcome'] += $tempOutcome;
                $hourRoom['surplus']= $hourRoom['income'] - $hourRoom['outcome'];
            }
            $detail[] = array(
                'date' => $dateIndex,
                'day' => $weekArray[date('w', $i)],
                'price' => $tempIncome-$tempOutcome,
            );
        }
        // 检查操作者是否子管理员,若是,需要根据房间权限过滤房间数据
        if (MODULE_NAME != 'Extend' && $needFilterRoom) {
            $orderRooms = fliterArrayByKey($orderRooms, 'roominfo_id', $roomAuthority);
        }

        $hourOccupancy = $occupancy = $hourSold = $sold = $price = 0;
        foreach ($orderRooms as $orderRoom) {
            switch ($orderRoom['status']) {
                case '1':
                    //表示已经出售但是还没有来住
                    if ($orderRoom['hour']>0){
                        $hourSold++;
                        $price+= $orderRoom['payment'];
                    } else {
                        $sold++;
                        $price+= round(($orderRoom['payment'] / $orderRoom['night']), 2);
                    }
                    break;
                case '2':
                    if ($orderRoom['hour']>0){
                        $hourSold++;
                        $hourOccupancy++;
                        $price+= $orderRoom['payment'];
                    } else {
                        $sold++;
                        $occupancy++;
                        $price+= round(($orderRoom['payment'] / $orderRoom['night']), 2);
                    }
                    break;
                case '3':
                    if ($orderRoom['hour']>0){
                        $hourSold++;
                        $hourOccupancy++;
                        $price+= $orderRoom['payment'];
                    } else {
                        $sold++;
                        $occupancy++;
                        $price+= round(($orderRoom['payment'] / $orderRoom['night']), 2);
                    }
                    break;
                case '4':
                    break;
                default :
                    break;
            }
        }
        $data['income'] = $income;
        $data['outcome'] = $outcome;
        $data['surplus'] = $data['income'] - $data['outcome'];
        if ($type == 1 || $type == 0) {
            $normalRoom['sold'] = $sold;
            $normalRoom['occupancy'] = $occupancy;
            $normalRoom['price'] =  empty($normalRoom['surplus']) ? 0 : number_format(($normalRoom['surplus'] / $sold), 2, '.', '');
            $normalRoom['occupancyRate'] = number_format($occupancy / count($roomInfos) * 100, 2, '.', '') . '%';

        }
        if ($type == 2 || $type == 0) {
            $hourRoom['sold'] = $hourSold;
            $hourRoom['occupancy'] = $hourOccupancy;
            $hourRoom['price'] =  empty($hourRoom['surplus']) ? 0 : number_format(($hourRoom['surplus'] / $hourSold), 2, '.', '');
            $hourRoom['occupancyRate'] =  number_format($hourOccupancy / count($hourRoomInfos) * 100, 2, '.', '') . '%';
        }
        $data['detail'] = $detail;
        if(!empty($hourRoom)){
            $data['hourRoom'] = $hourRoom;
        }
        if(!empty($normalRoom)){
            $data['normalRoom'] = $normalRoom;
        }   
        return $data;
    }

    /**
     * 实时查询当天收入情况
     * @modify zhangzhen 2017-06-05
     * @param integer $hotelId 客栈ID
     * @param date $date 查询日期
     * @return type
     */
    public function getMonthSummary($hotelId, $date) {
        return $this->__singleGet('_getMonthSummary', array($hotelId, $date));
    }
    public function _getMonthSummary($hotelId, $date) {
        $orderPayRecordModel = D('OrderPayRecord');
        $startDate = $date . ' 00:00:00';
        $endDate = date('Y-m-d H:i:s', strtotime('+1 months',strtotime($startDate)));
        $orderPayRecords = $orderPayRecordModel->getInfosBetweenHotelDate($hotelId, $startDate, $endDate);
        // 检查操作者是否子管理员,若是,需要根据房间权限过滤父订单
        if (MODULE_NAME != 'Extend' && !empty($orderPayRecords)) {
            // 获取房间权限权限
            $adminId = getUserId();
            $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
            if (!$adminAuthorityLogic->checkIsAdmin($adminId, $hotelId)) {
                $accountLogic = A('Common/Account', 'Logic');
                $roomAuthority = $accountLogic->getAdminRoomAuthority($adminId, $hotelId);

                if (empty($roomAuthority)) {
                    $orderPayRecords = array();
                } else {
                    // 删除无房间权限的父订单的收款记录
                    $orderIds = array_column($orderPayRecords, 'orderinfo_id');
                    $orderRoomModel = D('OrderRoom');
                    $orderRooms = $orderRoomModel->getInfoByOrder($orderIds);
                    // 过滤出有权限的子订单,再过滤出有权限的父订单
                    $orderRooms = fliterArrayByKey($orderRooms, 'roominfo_id', $roomAuthority);
                    $orderIds = array_column($orderRooms, 'orderinfo_id');
                    $orderPayRecords = fliterArrayByKey($orderPayRecords, 'orderinfo_id', $orderIds);
                }
            }
        }
        $orderRoomModel = D('OrderRoom');
        $orderRooms = $orderRoomModel->getInfoByOrder(array_column($orderPayRecords, 'orderinfo_id'));
        $orderRooms = getArrayValueAsIndex($orderRooms,'orderinfo_id');

        $receipt = $refund = $deposit = $refundDeposit = 0;
        //计算数据||type=0 收款  1= 押金 2=退款 3=退押金
        foreach ($orderPayRecords as $orderPayRecord) {
            if ($orderRooms[$orderPayRecord['orderinfo_id']]['month'] == 0 ) {
                continue;
            }
            switch ($orderPayRecord['type']) {
                case PAY_CHANGE_RECEIPT:// 收款
                    $receipt += (double)$orderPayRecord['pay'];
                    break;
                case PAY_CHANGE_DEPOSIT:// 收押金
                    $deposit += (double)$orderPayRecord['pay'];
                    break;
                case PAY_CHANGE_REFUND:// 退款
                    $refund += (double)$orderPayRecord['pay'];
                    break;
                case PAY_CHANGE_DEPOSIT_BACK:// 退押金
                    $refundDeposit += (double)$orderPayRecord['pay'];
                    break;
            }
        }

        //返回当天金额数据
        $data = array(
            'receipt' => $receipt,
            'deposit' => $deposit,
            'refund' => $refund,
            'refundDeposit' => $refundDeposit
        );
        return $data;
    }

    /**
     * 实时查询房间运营信息
     * @modify trainyao 2016-09-30 创建
     * @param  integer   $hotelId   客栈ID
     * @param  string   $date      需要实时查询
     * @return array              {roomTotal(房间总数), sold(已售出房间数), notSold(未售出房间数), occupancy(已入住订单数), checkInCount(已入住订单数), notCheckIn(未入住订单数), price(平均价格), occupancyRate(入住率)}
     */
    public function getMonthRoomReport($hotelId, $date) {
        return $this->__singleGet('_getMonthRoomReport', array($hotelId, $date));
    }
    protected function _getMonthRoomReport($hotelId, $date) {
        $startDate = $date . ' 00:00:00';
        $endDate = date('Y-m-d H:i:s', strtotime('+1 months',strtotime($startDate)));
        //计算房间总数
        $longRoomModel = D('LongRoom');
        $roomInfos = $longRoomModel->getInfosByHotel($hotelId);
        // 检查操作者是否子管理员,若是,需要根据房间权限过滤房间数据
        if (MODULE_NAME != 'Extend') {
            // 获取房间权限权限
            $adminId = getUserId();
            $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
            $needFilterRoom = false;
            if (!$adminAuthorityLogic->checkIsAdmin($adminId, $hotelId)) {
                $needFilterRoom = true;
                $accountLogic = A('Common/Account', 'Logic');
                $roomAuthority = $accountLogic->getAdminRoomAuthority($adminId, $hotelId);
                $roomInfos = fliterArrayByKey($roomInfos, 'id', $roomAuthority);
            }
        }
        $data = array();
        $data['roomTotal'] = $notSold = count($roomInfos);
        $occupancy = $notCheckIn = $sold = $price = $rest = 0;
        $orderRoomModel = D('OrderRoom');
        $orderRooms = $orderRoomModel->getInfoBetweenHotelMonth($hotelId, $startDate, $endDate);
        // 检查操作者是否子管理员,若是,需要根据房间权限过滤房间数据
        if (MODULE_NAME != 'Extend' && $needFilterRoom) {
            $orderRooms = fliterArrayByKey($orderRooms, 'roominfo_id', $roomAuthority);
        }
        $roomIds = [];
        foreach ($orderRooms as $orderRoom) {
            if (! in_array($orderRoom['roominfo_id'], $roomIds)){
                array_push($roomIds, $orderRoom['roominfo_id']);
                if($orderRoom['status'] == 1 || $orderRoom['status'] == 2){
                    $rest++;
                }
            }
            switch ($orderRoom['status']) {
                case '1':
                    //表示已经出售但是还没有来住
                    $notCheckIn++;
                    $notSold--;
                    $sold++;
                    $price+= $orderRoom['payment'];
                    break;
                case '2':
                    $notSold--;
                    $sold++;
                    $occupancy++;
                    $price+= $orderRoom['payment'];
                    break;
                case '3':
                    $notSold--;
                    $sold++;
                    $occupancy++;
                    $price+= $orderRoom['payment'];
                    break;
                case '4':
                    break;
                default :
                    break;
            }
        }
        $data['sold'] = $sold;
        $data['rest'] = $rest;
        $data['notSold'] = $notSold < 0 ? 0 : $notSold;
        $data['occupancy'] = $occupancy;
        $data['checkInCount'] = $occupancy;
        $data['notCheckIn'] = $notCheckIn;
        $data['price'] = empty($price) ? 0 : round(($price / $sold), 2);
        $data['occupancyRate'] = $occupancy / count($roomInfos);
        return $data;
    }

    /**
     * 获取收支明细
     * @modify wenhui 2017-12-18 创建
     * @param  integer   $hotelId   客栈ID
     * @param  string   $startDate   开始时间
     * @param  string   $endDate     结束时间
     * @param  integer   $pageIndex  当前页码
     * @return array
     */
    public function getHotelAccountView($hotelId, $type, $startDate, $endDate, $pageIndex = 1) {
        return $this->__singleGet('_getHotelAccountView', array($hotelId, $type, $startDate, $endDate, $pageIndex));
    }
    protected function _getHotelAccountView($hotelId, $type, $startDate, $endDate, $pageIndex) {
        // 获取具体收支信息记录
        $hotelNoteCostModel = D('HotelNoteCost');
        $hotelNoteCostInfo = $hotelNoteCostModel->getInfoByHotel($hotelId, null, $startDate, $endDate);

        // 获取支付方式信息用作补充
        $hotelLogic = A('Common/Hotel', 'Logic');
        $payResource = $hotelLogic->getHotelPay($hotelId, true, null, true);
        $payResource = getArrayValueAsIndex($payResource, 'id');

        // 获取记一笔项目信息用作补充
        $noteResource = $hotelLogic->getHotelNote($hotelId, true);
        $noteResource = getArrayValueAsIndex($noteResource, 'id');

        // 获取客栈所有管理者信息用作补充（包括删除的管理员）
        $adminHotelModel = D('AdminHotel');
        $adminLoginModel = D('AdminLogin');
        $userInfos = $adminHotelModel->getUserInfoByHotel($hotelId);
        $userIds = array_column($userInfos, 'adminlogin_id');
        $hotelInfos = $adminLoginModel->getInfoByAdminId($userIds);
        $hotelInfos = getArrayValueAsIndex($hotelInfos, 'id');

        // 补充信息
        $data = array();
        $income = 0;
        $outcome = 0;
        foreach ($hotelNoteCostInfo as $key => &$cost) {
            // 总收入与支出
            switch ($cost['type']) {
                case NOTE_INCOME:
                    $income += $cost['price'];
                    break;
                case NOTE_EXPENDITURE:
                    $outcome += $cost['price'];
                    break;
            }

            if (is_null($type)) {
                array_push($data, array(
                    'id' => $cost['id'],
                    'type' => $cost['type'],
                    'noteDate' => $cost['date'],
                    'noteName' => $noteResource[$cost['hotelnote_id']]['name'],
                    'hotelNoteId' => $cost['hotelnote_id'],
                    'notePrice' => $cost['price'],
                    'notePay' => $payResource[$cost['hotelpay_id']]['name'],
                    'hotelPayId' => $cost['hotelpay_id'],
                    'noteRemark' => $cost['remark'],
                    'noteOperator' => $hotelInfos[$cost['operator']]['name'],
                    'createtime' => strtotime($cost['createtime']),
                ));
            } else if ($type == $cost['type']) {
                array_push($data, array(
                    'id' => $cost['id'],
                    'type' => $cost['type'],
                    'noteDate' => $cost['date'],
                    'noteName' => $noteResource[$cost['hotelnote_id']]['name'],
                    'hotelNoteId' => $cost['hotelnote_id'],
                    'notePrice' => $cost['price'],
                    'notePay' => $payResource[$cost['hotelpay_id']]['name'],
                    'hotelPayId' => $cost['hotelpay_id'],
                    'noteRemark' => $cost['remark'],
                    'noteOperator' => $hotelInfos[$cost['operator']]['name'],
                    'createtime' => strtotime($cost['createtime']),
                ));
            }
        }
        unset($cost);

        // 按创建时间降序排序
        $data = my_sort($data, 'createtime', SORT_DESC);

        if (is_null($pageIndex)) {
            return $data;
        }

        $pageIndex = isset($pageIndex) ? $pageIndex : 1;
        // 生成第一页分页信息
        $hotelNoteCostInfo = createPageInfo($data, $pageIndex, C('NEWS_PAGE_SIZE'));
        return array(
            'income' => number_format($income, 2, '.', ''),
            'outcome' => number_format($outcome, 2, '.', ''),
            'info' => $hotelNoteCostInfo['data'],
            'itemtotal' => $hotelNoteCostInfo['total'],
            'pagetotal' => $hotelNoteCostInfo['pageTotal'],
            'current' => $hotelNoteCostInfo['current'],
        );
    }


    /**
     * 返回客栈日期段内的其他消费细明
     * @modify wenhui 2017-12-19
     * @param integer $hotelId 客栈ID
     * @param date $startDate 查询开始日期 2016-01-19
     * @param date $endDate 查询结束日期
     * @param bool $otherType 是否获取其他消费 true
     * @param integer $pageIndex 页码
     * @return array ()
     */
    public function getOrderCostDetail($hotelId, $startDate, $endDate, $otherType = true, $pageIndex = null, $orderId = null) {
        $startDate = $startDate . ' 00:00:00';
        $endDate = $endDate . ' 23:59:59';

        $orderInfoModel = D('OrderInfo');
        $orderRoomModel = D('OrderRoom');
        $orderPayRecordModel = D('OrderPayRecord');

        if (is_null($orderId)) {
            $orderPayRecords = $orderPayRecordModel->getInfosBetweenHotelDate($hotelId, $startDate, $endDate, $otherType);
        } else {
            $orderPayRecords = $orderPayRecordModel->getInfosByOrderId($orderId);
        }
        $orderPayRecords = getArrayValueAsIndex($orderPayRecords, 'orderinfo_id', true);
        $orderIds = array_keys($orderPayRecords);

        $orderInfos = $orderInfoModel->getInfoByOrderAndDate(['in', $orderIds]);
        $orderInfos = getArrayValueAsIndex($orderInfos, 'id');

        $orderRoomInfo = $orderRoomModel->getInfoByOrder($orderIds, false);
        $orderRoomInfo = getArrayValueAsIndex($orderRoomInfo, 'orderinfo_id', true);

        $orderLogic = A('Common/Order', 'Logic');
        $hotelLogic = A('Common/Hotel', 'Logic');
        // 客栈支付方式
        $payResource = $hotelLogic->getHotelPay($hotelId);
        $payResource = getArrayValueAsIndex($payResource, 'id');
        // 其他消费项目数据
        $otherCostData = $hotelLogic->getHotelOtherCost($hotelId, true);
        $otherCostData = getArrayValueAsIndex($otherCostData, 'id');
        // 补充数据
        $data = array();
        foreach ($orderPayRecords as $key => $orderPayRecordItem) {
            $totalPrice = 0;
            $payRecord = array();
            foreach ($orderPayRecordItem as $orderId => $payRecordItem) {

                $totalPrice += $payRecordItem['pay'];
                if ($payRecordItem['hotelpay_id'] != 0) {
                    $notePay = $payResource[$payRecordItem['hotelpay_id']]['name'];
                } else {
                    $notePay = $orderLogic->payChangeTypeMap[LANG_SET][4];
                }
                $payRecord[] = array(
                    'noteTime' => date('m/d H:i', strtotime($payRecordItem['createtime'])),
                    'noteName' => $otherCostData[$payRecordItem['type']]['name'],
                    'notePrice' => $payRecordItem['pay'],
                    'notePay' => $notePay,
                );
            }
            unset($payRecordItem);

            $roomStartTime = $orderRoomInfo[$orderPayRecordItem[0]['orderinfo_id']][0]['startdate'];
            $roomStartTime = date('m/d', strtotime($roomStartTime));
            $roomEndTime = $orderRoomInfo[$orderPayRecordItem[0]['orderinfo_id']][0]['enddate'];
            $roomEndTime = date('m/d', strtotime($roomEndTime));

            $roomName = $orderRoomInfo[$orderPayRecordItem[0]['orderinfo_id']][0]['roominfo_name'];
            $room = $roomName . ',' .  $roomStartTime . '-' . $roomEndTime;
            $status = $orderLogic->statusMap[LANG_SET][$orderInfos[$orderPayRecordItem[0]['orderinfo_id']]['status']];

            $data[] = array(
                'orderId' => $orderPayRecordItem[0]['orderinfo_id'],
                'name' => $orderInfos[$orderPayRecordItem[0]['orderinfo_id']]['name'],
                'room' => $room,
                'totalPrice' => number_format($totalPrice, '2', '.', ''),
                'status' => $status,
                'detail' => $payRecord,
                'sortTime' => strtotime($orderPayRecordItem[0]['createtime']),
            );
        }
        unset($orderPayRecordItem);

        // 不分页
        if (is_null($pageIndex)) {
            return $data;
        }

        /**
         *  排序
         *  排序方式 推荐客栈按点击量  有城市搜索 按最近距离
         *  SORT_ASC - 默认，按升序排列。(A-Z)
         *  SORT_DESC - 按降序排列。(Z-A)
         *  随后可以指定排序的类型：
         *  SORT_REGULAR - 默认。将每一项按常规顺序排列。
         *  SORT_NUMERIC - 将每一项按数字顺序排列。
         *  SORT_STRING - 将每一项按字母顺序排列
         */
        if (!empty($data)) {
            $data = my_sort($data, 'sortTime', SORT_DESC, SORT_NUMERIC);
        }

        // 生成第一页分页信息
        $data = createPageInfo($data, $pageIndex, C('NEWS_PAGE_SIZE'));
        return array(
            'info' => $data['data'],
            'itemtotal' => $data['total'],
            'pagetotal' => $data['pageTotal'],
            'current' => $data['current'],
        );
    }
}
